package com.le.tester.tip;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.le.tester.dto.FileDto;
import com.le.tester.dto.GenSQLDto;
import com.le.tester.dto.oss.RenameFileDto;
import com.le.tester.utils.FileNodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * createTime：2024-08-06 13:47
 * description：oss重命名文件
 */
public class OSSRenameFile {

    //推荐使用创建线程池
    private static final ExecutorService pool = new ThreadPoolExecutor(3, 3,
            1, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    private static final String endpointGZ = "https://oss-cn-guangzhou.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tDbQg5hC7tRAPDVrN6v";
    private static final String accessKeySecret = "NhgeBPVAY6AfbwbqyY29ybz5hfSwPw";

    private static final String URLPrefix = "https://";
    private static final String domainGZ = "oss-cn-guangzhou.aliyuncs.com";


    private static OSS ossClientGZ = new OSSClientBuilder().build(endpointGZ, accessKeyId, accessKeySecret);

    private static final String dataURL = "E:\\Desktop\\testAlbumProd.json";


    //重新命名文件
    public static List<FileDto> renameFileBat(RenameFileDto renameFile) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String bucketName = renameFile.getBucketName();
        String folderName = renameFile.getFolderName();
        List<FileDto> fileInfoList = renameFile.getFileInfoList();
        if (StringUtils.isBlank(bucketName) || StringUtils.isBlank(folderName)
                || CollectionUtils.isEmpty(fileInfoList)) {
            throw new IllegalArgumentException();
        }
        try {
            for (FileDto item : fileInfoList) {
                String fileUrl = item.getFileUrl();
                String fileName = URLEncoder.createDefault().encode(FileNodeUtil.getFileMainName(fileUrl), StandardCharsets.UTF_8);
                String fileSuffix = FileNameUtil.getSuffix(fileUrl);
                String sourceKey = URLUtil.getPath(fileUrl).replaceFirst("/", "");
                // dev/shop/109/fileName_timestamp.fileSuffix
                String destinationKey = folderName + "/" + fileName + "_" + timestamp + "." + fileSuffix;

                // 将examplebucket下的srcobject.txt拷贝至同一Bucket下的destobject.txt。
                ossClientGZ.copyObject(bucketName, sourceKey, bucketName, destinationKey);
                // 删除srcobject.txt。
                ossClientGZ.deleteObject(bucketName, sourceKey);

                //新的文件路径
                String newFileUrl = URLPrefix + bucketName + "." + domainGZ + "/" + destinationKey;
                item.setFileUrl(newFileUrl);

            }
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        } finally {
            if (Objects.nonNull(ossClientGZ)) {
                ossClientGZ.shutdown();
            }
        }
        return fileInfoList;

    }

    //获取数据
    public static List<FileDto> getData() {
        File file = new File(dataURL);
        String content = FileUtil.readString(file, StandardCharsets.UTF_8);
        JSONObject record = JSONObject.parseObject(content);
        String ossPathStr = record.get("RECORDS").toString();

        return JSONArray.parseArray(ossPathStr, FileDto.class);
    }

    //oss文件路径更新
    static class OssFileUrlUpdateTask implements Runnable {
        public String bucketName = "bojuematerial-prudcut-public";
        public String folderName = "dev/album";


        public String columnName = "icon";
        public String tableName = "album_products";
        public String onlyIdName = "ap_id";

        @Override
        public void run() {
            RenameFileDto renameFileDto = new RenameFileDto();
            List<FileDto> initFileList = OSSRenameFile.getData();
            renameFileDto.setFileInfoList(initFileList);
            renameFileDto.setFolderName(folderName);
            renameFileDto.setBucketName(bucketName);
            List<FileDto> renameFileList = OSSRenameFile.renameFileBat(renameFileDto);

            if (!CollectionUtils.isEmpty(renameFileList)) {
                GenSQLDto genSQL = new GenSQLDto();
                genSQL.setColumnName(columnName);
                genSQL.setTableName(tableName);
                genSQL.setOnlyIdName(onlyIdName);
                String sql = DataUpdate.genSql(renameFileList, genSQL);
                try {
                    DataUpdate.execSql(sql);
                } catch (Exception e) {
                    System.out.println("exec sql update exception,reason is " + e);
                }
            }


        }

    }


    public static void main(String[] args) {

        CompletableFuture.runAsync(new OssFileUrlUpdateTask(), pool);
        pool.shutdown();
    }
}
